package com.archstoday.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.BackgroundColorSpan;
import android.text.style.ForegroundColorSpan;
import android.text.style.UnderlineSpan;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;

import com.archstoday.R;
import com.archstoday.common.AsRes;
import com.archstoday.common.SpfUtils;
import com.archstoday.entity.BaseEntity;
import com.archstoday.entity.LoginEntity;
import com.archstoday.utils.ToolUtils;
import com.base.http.common.BaseHttpClient;
import com.base.utils.ImageUtil;
import com.base.utils.LogUtil;
import com.base.utils.MySharedPreferencesMgr;
import com.base.utils.StringUtil;

import java.util.Timer;
import java.util.TimerTask;

/**
 * 登录界面
 */
public class LoginActivity extends AsScrollBaseActivity {

    private TextView mTitleTv;
    private EditText mPhoneEdit, mCodeEdit;
    private TextView mCodeTv;
    private CheckBox mAgreementBtn;
    private TextView mAgreementTv;

    private MyTimeTask mTimeTask;
    private Timer timer;
    private int recLen;

    private String mPhoneStr, mCodeStr;

    @Override
    protected void initView(Bundle bundle) {
        setContentView(R.layout.activity_login);
        mTitleTv = (TextView) findViewById(R.id.title_tv);
        mPhoneEdit = (EditText) findViewById(R.id.login_phone_edit);
        mCodeEdit = (EditText) findViewById(R.id.login_code_edit);
        mCodeTv = (TextView) findViewById(R.id.login_get_code_btn);
        mAgreementBtn = (CheckBox) findViewById(R.id.login_agreement_check);
        mAgreementTv = (TextView) findViewById(R.id.login_agreement_tv);
    }

    @Override
    protected void initData(Bundle bundle) {
        mTitleTv.setText(R.string.login);

        String str = getString(R.string.login_agreement);
        SpannableString content = new SpannableString(str);
        content.setSpan(new UnderlineSpan(), str.indexOf("《"), str.length(),
                Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        content.setSpan(new ForegroundColorSpan(ImageUtil.getColor(mContext, R.color.green_text)),
                str.indexOf("《"), str.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        mAgreementTv.setText(content);
    }

    @Override
    protected void initListener() {
        setOnClickListener(R.id.back_btn);
        setOnClickListener(R.id.login_get_code_btn);
        setOnClickListener(R.id.login_btn);
        setOnClickListener(R.id.login_agreement_tv);
    }

    @Override
    public void treatClickEvent(int id) {
        switch (id) {
            case R.id.back_btn:
                appFinish();
                break;
            case R.id.login_get_code_btn:
                mPhoneStr = mPhoneEdit.getText().toString();
                if (StringUtil.isEmpty(mPhoneStr)) {
                    showToast(R.string.login_phone_null);
                } else if (!StringUtil.isMobileNO(mPhoneStr)) {
                    showToast(R.string.login_phone_error);
                } else {
                    getCode();
                }
                break;
            case R.id.login_btn:
                mPhoneStr = mPhoneEdit.getText().toString();
                mCodeStr = mCodeEdit.getText().toString();
                if (StringUtil.isEmpty(mPhoneStr)) {
                    showToast(R.string.login_phone_null);
                } else if (!StringUtil.isMobileNO(mPhoneStr)) {
                    showToast(R.string.login_phone_error);
                } else if (StringUtil.isEmpty(mCodeStr)) {
                    showToast(R.string.login_code_null);
                } else if (!mAgreementBtn.isChecked()) {
                    showToast(R.string.login_agreement_false);
                } else {
                    getEvent(mApp.E_LOGIN, mApp.PAGE_TYPE_LOGIN);
                    login();
                }
                break;
            case R.id.login_agreement_tv:
                Intent intent = new Intent(mContext, WebActivity.class);
                intent.putExtra("title", "用户协议");
                intent.putExtra("url", "http://archs-apires.oss-cn-beijing.aliyuncs.com/userAgreement/userAgreement.html");
                startActivity(intent);
                break;
        }
    }

    private void getCode() {
        initParameter();
        mParams.put("mobile", mPhoneStr);

        sendEncryptPostRequest(AsRes.getInstance().getUrl(AsRes.GET_CODE),
                AsRes.GET_CODE, mParams, BaseEntity.class);
    }

    private void login(){
        initParameter();
        mParams.put("loginName", mPhoneStr);
        mParams.put("mbCode", mCodeStr);
        mParams.put("loginType", "phone");

        sendEncryptPostRequest(AsRes.getInstance().getUrl(AsRes.LOGIN),
                AsRes.LOGIN, mParams, LoginEntity.class);
    }

    @Override
    protected void onSuccess(String content, BaseHttpClient client, Object parse) {
        if (client.getUrlIdentifier() == AsRes.GET_CODE) {
            BaseEntity entity = (BaseEntity) parse;
            if (ToolUtils.isSuccess(entity.getStatus())) {
                if (mTimeTask != null) {
                    mTimeTask.cancel();
                }
                timer = new Timer();
                mTimeTask = new MyTimeTask();
                mCodeTv.setEnabled(false);
                recLen = 60;
                timer.schedule(mTimeTask, 1000, 1000);
            }
            showToast(entity.getMsg());
        } else if (client.getUrlIdentifier() == AsRes.LOGIN) {
            LoginEntity entity = (LoginEntity) parse;
            if (ToolUtils.isSuccess(entity.getStatus())) {
                MySharedPreferencesMgr.setString(SpfUtils.USER_ID, String.valueOf(entity.getData().getUserId()));
                MySharedPreferencesMgr.setString(SpfUtils.USER_TOKEN, entity.getData().getToken());
                LogUtil.log_e("HX", "token===>"+MySharedPreferencesMgr.getString(SpfUtils.USER_TOKEN, ""));
                appFinish();
            }
            showToast(entity.getMsg());
        }
    }

    class MyTimeTask extends TimerTask {
        @Override
        public void run() {
            recLen--;
            Message message = new Message();
            handler.sendMessage(message);
        }
    }

    Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg){
            mCodeTv.setText(recLen + getString(R.string.login_resend_code));
            if(recLen < 0){
                if (mTimeTask != null) {
                    mTimeTask.cancel();
                }
                timer.cancel();
                mCodeTv.setEnabled(true);
                mCodeTv.setText(R.string.login_code);
            }
        }
    };
}